package coml.jiyun.hp.day04;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mMainImg;
    /**
     * 上传
     */
    private Button mMainShangchuan;
    /**
     * 下载
     */
    private Button mMainXiazai;
    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private boolean down;
    /**
     * 0%
     */
    private CircleProgressBar mCpb;
    private OkHttpClient okHttpClient;
    private String url = "http://cdn.banmi.com/banmiapp/apk/banmi_330.apk";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mMainImg = (ImageView) findViewById(R.id.main_img);
        mMainShangchuan = (Button) findViewById(R.id.main_shangchuan);
        mMainXiazai = (Button) findViewById(R.id.main_xiazai);
        mCpb = (CircleProgressBar) findViewById(R.id.cpb);



        mMainImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开相册
                Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 200);
            }
        });

        // startxj();//打开相机

    }

    private void startxj() {
        //启动 相机
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), 200);
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case 150:
//                if (resultCode == RESULT_OK) {
//                    //获取拍的照片
//                    Bitmap bitmap = (Bitmap) data.getExtras().get("data");
//                    // 将Bitmap对象设置到图片组件上
//                    mMainImg.setImageBitmap(bitmap);
//                }
//                break;
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    // 通过uri的方式返回，设置到图片组件上
                    mMainImg.setImageURI(uri);
                    System.out.println("----------------uri--------------");
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.main_shangchuan:
                Upload(new File("/storage/emulated/0/lhz.jpg"));
                break;
            case R.id.main_xiazai:
                String path = "/storage/emulated/0/a.apk";
                download(url, path);
                initload();
                break;
        }
    }

    private void initload() {
        if (!down) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 101; i++) {
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        down = true;
                        if (i == 100) {
                            down = false;
                        }
                        mCpb.setProgress(i);
                    }
                }
            }).start();
        }
    }

    private void download(String url, String path) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        new OkHttpClient()
                .newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("TAG", "onFailure: ");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //请求成功
                        Log.d("TAG", "onResponse: ");
                        InputStream inputStream = response.body().byteStream();
                        saveFile(path, inputStream, response.body().contentLength());
                    }
                });
    }

    private void saveFile(String path, InputStream inputStream, long contentLength) {
        byte[] bytes = new byte[2048];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
            // ShowToast("下载成功");
            Log.d("TAG", "下载成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void Upload(File file) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        MultipartBody build = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("key", "caca")
                .addFormDataPart("file", file.getName(), requestBody)
                .build();
        Request request = new Request.Builder()
                .url("http://yun918.cn/study/public/file_upload.php")
                .post(build)
                .build();
        okHttpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("TAG", "onFailure: " + e.toString());

                        //ShowToast("上传成功");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d("TAG", "onResponse: " + response.body().string());
                    }
                });
    }
//    String uri="/sdcard/shouye.png";
}